import {ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {NzMessageService} from "ng-zorro-antd/message";
import {NzModalService} from "ng-zorro-antd/modal";
import {Product2Service} from "../../../../shared/services/product2/product.service";
import {ConfigService} from "../../../../shared/services/config.service";
import {ActivatedRoute, Router} from "@angular/router";
import * as moment from 'moment';
import {Sell2Service} from "../../../../shared/services/product2/sell.service";

@Component({
    selector: 'app-product-detail',
    templateUrl: './product-detail.component.html',
    styleUrls: ['./product-detail.component.scss']
})
export class ProductDetailComponent implements OnInit {

    source: any;
    object: any;

    _subscriptions = [];

    option: any = {
        catalog: 'all',
        category: 'all',
        catalogs: [],
        categories: [],
        sell: {
            range: [],
            current: 1,
            fields: ['code'],
            keyword: '',
            paid: 'all'
        }
    };

    sell_page: any = [];
    sells: any = [];
    _sells: any = [];

    constructor(private router: Router, private route: ActivatedRoute, private sellService: Sell2Service, private productService: Product2Service, public configService: ConfigService, 
                private modal: NzModalService, private message: NzMessageService) {
    }

    ngOnInit() {
        this.option.catalogs = this.configService.config.product.catalogs;
        this._subscriptions.push(this.route.data.subscribe(res => {
            this.source = res.data;
            this.object = JSON.parse(JSON.stringify(this.source));
            this.option.catalog = this.option.catalogs.find(item => item.code == this.object.catalog);
            this.option.category = this.option.catalog.children.find(item => item.code == this.object.category);
            //this.object = this.source.clone();
            this.option.sell.range = [moment().startOf('month').toDate(), moment().endOf('month').toDate()];
           
            this.sellService.getByDate(moment().startOf('month'), moment().endOf('month')).subscribe( res => {
                this._sells = res.filter(item => item.product._id == this.object._id);
                this.filterSell();
            });
          
        }));
    }

    ngOnDestroy(): void {
        this._subscriptions.forEach( sub => {
            sub.unsubscribe();
        });
    }

    changeSellDate(result: Date[]): void {
        this.sellService.getByDate(moment(result[0]).startOf('day'), moment(result[1]).endOf('day')).subscribe( res => {
            this._sells = res.filter(item => item.product._id == this.object._id);
            this.filterSell();
        });
    }

    filterSell() {
        this.sells = this._sells.filter(item => {
            if (this.option.sell.paid != 'all' && !!item.paid != this.option.sell.paid) {
                return false;
            }
            if (this.option.sell.keyword.trim() === '') {
                return true;
            } else {
                return this.option.sell.fields.some(field => {
                    if (item[field].indexOf(this.option.sell.keyword) != -1) {
                        return true;
                    }
                    return false;
                });
            }
        });
        this.sell_page = this.sells.slice((this.option.sell.current - 1) * 10, this.option.sell.current * 10);
    }

    totalSell() {
        return this.sells.reduce((acc, cur) => {
            return acc + cur.price * cur.amount;
        },0);
    }

    compareObject(g1: any, g2: any): boolean {
        return g1 && g2 ? g1._id === g2._id : g1 === g2;
    }

    cancel(){
        this.object = JSON.parse(JSON.stringify(this.source));
        //this.object = this.source.clone();
        this.router.navigate(['list'], {relativeTo: this.route.parent});
    }

    save(){
        this.object.catalog = this.option.catalog.code;
        this.object.category = this.option.category.code;
        this.productService.update(this.object)
            .subscribe(res => {
                if (res.result) {
                    this.message.create('success', '保存成功！');
                    this.productService.emit('update', this.object);
                } else {
                    this.message.create('warning', '名称已存在！');
                }
            });
    }

    delete(){
        this.modal.confirm({
            nzTitle: '提示！',
            nzContent: `是否确认删除？`,
            nzOkText: '确定',
            nzOkType: 'primary',
            nzOnOk: () => {
                this.productService.delete(this.object._id)
                    .subscribe(res => {
                        if (res.result){
                            this.message.create('success', '删除成功！');
                            this.productService.emit('delete', this.object);
                            this.router.navigate(['list'], {relativeTo: this.route.parent});
                        } else {
                            this.message.create('warning', '删除失败！');
                        }
                    });
            }
        });
    }

    onPictureChange(pictures) {
        this.object.pictures = pictures;
    }

    compareEntity(g1: any, g2: any): boolean {
        return g1 && g2 ? g1._id === g2._id : g1 === g2;
    }

    compareElement(g1: any, g2: any): boolean {
        return g1 && g2 ? g1.code === g2.code : g1 === g2;
    }
}
